package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.FollowMapper;
import com.hmdp.service.IFollowService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private IUserService userService;

    /**
     * @param: [followUserId, isFollow]
     * @return: com.hmdp.dto.Result
     * @description: 关注或取关
     **/
    @Override
    public Result follow(Long followUserId, Boolean isFollow) {
        // 获取用户id
        Long userId = UserHolder.getUser().getId();
        String key = "follows:" + userId;
        if (isFollow) {
            // true表示关注
            // 创建Follow对象
            Follow follow = new Follow();
            follow.setUserId(userId);
            follow.setFollowUserId(followUserId);
            follow.setCreateTime(LocalDateTime.now());
            // 保存到数据库
            boolean flag = save(follow);
            if (flag) {
                // redis set 用于取交集判断共同关注
                stringRedisTemplate.opsForSet().add(key, followUserId.toString());
                log.info("[Log]: 关注成功");
            }
        } else {
            // false表示取关
            // 根据userid和followUserId删除对应的表项即可
            boolean flag = remove(new QueryWrapper<Follow>()
                    .eq("user_id", userId)
                    .eq("follow_user_id", followUserId));
            if (flag) {
                stringRedisTemplate.opsForSet().remove(key, followUserId);
                log.info("[Log]: 取关成功");
            }
        }
        return Result.ok();
    }

    /**
     * @param: [followUserId]
     * @return: com.hmdp.dto.Result
     * @description: 判断是否关注，关注返回 true
     **/
    @Override
    public Result isFollow(Long followUserId) {
        // 获取用户id
        Long userId = UserHolder.getUser().getId();
        Integer count = query().eq("user_id", userId)
                .eq("follow_user_id", followUserId).count();
        return Result.ok(count > 0);
    }

    /**
     * @param: [id]
     * @return: com.hmdp.dto.Result
     * @description: 查询交集
     **/
    @Override
    public Result followCommons(Long id) {
        Long userId = UserHolder.getUser().getId();
        String keyUser = "follows:" + userId;
        String keyFollow = "follows:" + id;
        // 查询交集
        Set<String> intersect = stringRedisTemplate.opsForSet().intersect(keyUser, keyFollow);
        if (intersect == null || intersect.isEmpty()) {
            // 防止空指针
            log.info("[Log]: 交集为空");
            return Result.ok(Collections.emptyList());
        }
        List<Long> ids = intersect.stream().map(Long::valueOf).collect(Collectors.toList());
        List<User> users = userService.listByIds(ids);
        List<UserDTO> userDTOList = users.stream().map(user -> BeanUtil.copyProperties(user, UserDTO.class)).collect(Collectors.toList());
        log.info("[Log]: 查询关注用户的交集--{}",userDTOList);
        return Result.ok(userDTOList);
    }
}
